<template>
  <vxe-modal
    resize
    esc-closable
    width="70%"
    height="80%"
    showFooter
    v-model="formVisible"
    :loading="formLoading"
    @hide="formClose"
  >
    <template slot="title">
      <span>成员表单</span>
    </template>
    <template>
      <el-scrollbar class="scrollbar-handle">
        <el-main>
          <!-- 表格  -->
          <vxe-grid
            ref="mainTable"
            :height="tableHeight"
            :toolbar="tableToolbar"
            :columns="tableColumn"
            :data="filtedData"
            row-id="B_UserId"
            :checkbox-config="{ checkRowKeys:checkedUserIds, reserve:true, trigger: 'cell', highlight: true }"
            @checkbox-change="singleCheckChange"
            @checkbox-all="allCheckChange"
            v-if="vif"
          >
            <!-- 多条件查询 -->
            <template v-slot:toolbar_search>
              <vxe-form>
                <vxe-form-item span="8">
                  <rayd-select
                    placeholder="请选择组织"
                    :options="manaTreeList"
                    v-model="B_ManaframeId"
                    tree-config
                    @change="resetDep"
                  />
                </vxe-form-item>
                <vxe-form-item span="8">
                  <rayd-select
                    placeholder="请选择部门"
                    :options="depTreeList"
                    v-model="B_DepartmentId"
                    tree-config
                  />
                </vxe-form-item>
                <vxe-form-item span="8">
                  <vxe-input v-model="filterName" suffix-icon="el-icon-search" placeholder="快速查询" clearable></vxe-input>
                </vxe-form-item>
              </vxe-form>
            </template>
            <!-- 业务按钮 -->
            <template v-slot:toolbar_buttons></template>
            <!-- 顶部模板 -->
            <template v-slot:top>
              <el-alert
                type="success"
                :title="`已选择 ${checkedUserIds.length} 项`"
                :closable="false"
                show-icon
              ></el-alert>
            </template>
          </vxe-grid>
        </el-main>
      </el-scrollbar>
    </template>
    <template slot="footer">
      <el-button type="primary" @click="formSubmit">保存</el-button>
      <el-button @click="formVisible=false">取消</el-button>
    </template>
  </vxe-modal>
</template>

<script>
//用户、部门数据皆深度获取
import { UserRelation, User, Department, Manaframe } from "@/api";
import XEUtils from "xe-utils";
export default {
  name: "Assign",
  props: {
    //组织架构主键
    manaId: {
      type: String,
      required: true
    },
    //部门主键
    depId: {
      type: String,
      required: false
    },
    //分类:1-角色2-岗位
    category: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      /* vxe-grid */
      tableData: [], //表格实体
      tableHeight: 390, //表格高度
      //工具栏配置
      tableToolbar: {
        zoom: true,
        custom: true
      },
      //列配置
      tableColumn: [
        {
          type: "seq",
          title: "序号",
          width: 80,
          align: "left",
          fixed: "left"
        },
        {
          type: "checkbox",
          width: 60,
          fixed: "left"
        },
        {
          type: "html",
          field: "B_RealName",
          title: "用户姓名",
          sortable: true
        },
        { type: "html", field: "B_Account", title: "用户账号", sortable: true },
        { type: "html", field: "B_EnCode", title: "用户工号", sortable: true }
      ],
      /* v-if组件重渲染 */
      vif: false,
      /* 实体数据 */
      objectId: "", //对象主键
      B_ManaframeId: "", //组织架构主键
      B_DepartmentId: "", //部门主键
      filterName: "", //快速查询
      manaTreeList: [], //架构树型数据
      depTreeList: [], //部门树型数据
      checkedUserIds: [], //对象已有用户
      formVisible: false, //表单可见
      formLoading: false
    };
  },
  computed: {
    //单页快速查询
    filtedData() {
      let tb = this.tableData;
      //部门、组织搜索
      if (this.B_DepartmentId !== this.depId) {
        tb = this.tableData.filter(o => {
          return o.B_DepartmentId === this.B_DepartmentId;
        });
      } else if (this.B_ManaframeId !== this.manaId) {
        tb = this.tableData.filter(o => {
          return o.B_ManaframeId === this.B_ManaframeId;
        });
      } 
      //快搜
      let filterName = XEUtils.toString(this.filterName).trim().toLowerCase();
      if (filterName) {
          let filterRE = new RegExp(filterName, "gi");
          //获取表格的可视列的field
          let searchProps = [];
          this.$refs["mainTable"].getColumns().forEach((item, index) => {
              if (item.property) {
                  searchProps.push(item.property);
              }
          })
          //树型快搜
          const options = { children: 'children' }
          const rest = XEUtils.searchTree(tb, item => searchProps.some(key => XEUtils.toString(item[key]).toLowerCase().indexOf(filterName) > -1), options)
          //高亮匹配条件
          XEUtils.eachTree(rest, item => {
              searchProps.forEach(key => {
                  item[key] = XEUtils.toString(item[key]).replace(filterRE, match => `<span style='color: #000;background-color: #ffff00;'>${match}</span>`)
              })
          }, options)
          // 搜索之后默认展开所有子节点
          this.$nextTick(() => {
              this.$refs["mainTable"].setAllTreeExpand(true)
          })
          // 返回rest中对于每一项都增设 children 属性
          return rest
      }
      return tb;
    }
  },
  created() {
    //初始化
    this.init();
  },
  methods: {
    //初始化
    init() {},
    //表单开启（父组件调用 objectId: 角色Id/岗位Id）
    formOpen(objectId) {
      //打开表单
      this.formVisible = this.formLoading = true; 
      Promise.all([
        //获取架构树型数据
        Manaframe.GetTreeList().then(res => {
          this.manaTreeList = this.util.getTreeSubNodes(res, this.manaId);
        }),
        //获取部门树形数据
        Department.GetTreeList({
          B_ManaframeId: this.manaId,
          isDeep: false
        }).then(res => {
          if (this.depId) {
            this.depTreeList = this.util.getTreeSubNodes(res,this.depId);
          } else {
            this.depTreeList = res;
          }
        }),
        //初始化该对象所拥有的所有用户
        UserRelation.GetUserIdList(objectId).then(res => {
          this.checkedUserIds = res; //初始化勾选
        })
      ]).then(result => {
        //加载表格数据
        User.GetListByManaDepId({
          B_ManaframeId: this.manaId,
          B_DepartmentId: this.depId,
          isDeep: true
        }).then(res => {
          //初始化Data
          this.objectId = objectId;
          this.B_ManaframeId = this.manaId;
          this.B_DepartmentId = this.depId;
          this.tableData = res;
          this.vif = true; //组件重新渲染
          this.formLoading = false; 
        });
      });
    },
    //表单提交
    formSubmit() {
      //提交
      UserRelation.Save({
        category: this.category,
        objectId: this.objectId,
        userIds: this.checkedUserIds
      }).then(res => {
        this.formVisible = false; //关闭弹窗
      });
    },
    //表单关闭
    formClose() {
      this.$refs["mainTable"].clearCheckboxRow();
      this.vif = false; //组件重新渲染

      this.objectId = ""; //对象主键
      this.B_ManaframeId = ""; //组织架构主键
      this.B_DepartmentId = ""; //部门主键
      this.filterName = ""; //快速查询
      this.manaTreeList = []; //架构树型数据
      this.depTreeList = []; //部门树型数据
      this.checkedUserIds = []; //对象已有用户
    },
    //部门树形数据联动获取
    resetDep(val) {
      this.B_DepartmentId = this.depId; //重置部门选择
      Department.GetTreeList({
        B_ManaframeId: val,
        isDeep: false
      }).then(res => { this.depTreeList = res; });
    },
    //单选回调
    singleCheckChange({ checked, row, reserves }) {
      if (checked) {
        //选中
        this.checkedUserIds = this.util.arrCombine(this.checkedUserIds, [
          row.B_UserId
        ]);
      } else {
        //非选中
        this.checkedUserIds = this.util.arrSplice(this.checkedUserIds, row.B_UserId);
      }
    },
    //全选回调
    allCheckChange({ checked }) {
      let temp = [];
      this.filtedData.forEach(o => {
        temp.push(o.B_UserId);
      });
      if (checked) {
        //选中
        this.checkedUserIds = this.util.arrCombine(this.checkedUserIds, temp);
      } else {
        //非选中
        temp.forEach(val => {
          this.checkedUserIds = this.util.arrSplice(this.checkedUserIds, val);
        });
      }
    }
  }
};
</script>

<style lang="less" scoped>
</style>